import { useEffect, useMemo } from 'react'
import { Badge, Button, Modal, Popover, Tooltip } from 'antd'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { RouteTplShow } from '../../components/FieldShowComponents'
import { getBooleanName, getLogisticsStatusName, getRouteNodeName, getRouteTypeName } from '../utils'
import { AddOrEditTplRouteDrawer } from './AddOrEditTplRouteDrawer'
import { Filter } from './Filter'
import { ITplRouteListItem, TCellParams, TCol } from './interface'
import { useBoundStore } from './store'
import { useTplRouteList } from './useTplRouteList'
import { popupSlot } from './utils'
import styles from './styles.module.less'

const ActionCell = ({ value }: TCellParams<'routeId'>) => {
  const delTplRoute = useBoundStore(v => v.delTplRoute)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)
  if (value == null) return
  return (
    <>
      <Tooltip title="编辑">
        <Button
          type="link"
          icon={<EditOutlined />}
          onClick={() => {
            if (value == null) return
            AddOrEditTplRouteDrawer.open({
              routeId: value,
              onSuccess: () => {
                setReqData({ page: 1 })
                getData()
              },
            })
          }}
        />
      </Tooltip>
      <Tooltip title="删除">
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => {
            Modal.confirm({
              title: '确认要删除吗？',
              onOk: () => delTplRoute(value),
            })
          }}
        />
      </Tooltip>
    </>
  )
}

const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'templateCn':
    case 'templateEn': {
      const { value } = p as TCellParams<'templateCn' | 'templateEn'>
      return <RouteTplShow value={value} />
    }
    case 'dynamicField': {
      const { data: { dynamicFieldList } = {} } = p as TCellParams<'dynamicField'>
      if (!dynamicFieldList?.length) return
      return (
        <Popover
          destroyTooltipOnHide
          content={
            dynamicFieldList.length > 1 && (
              <div style={{ maxHeight: 200, minWidth: 130, overflow: 'auto' }}>
                {dynamicFieldList.map(d => (
                  <div key={d}>{d}</div>
                ))}
              </div>
            )
          }
        >
          <a>
            {dynamicFieldList[0].replace(/^\s*{{(.+)}}\s*$/, '$1')}
            {dynamicFieldList.length > 1 && `(${dynamicFieldList.length})`}
          </a>
        </Popover>
      )
    }
    case 'routeType': {
      const { value, valueFormatted } = p as TCellParams<'routeType'>
      if (value == null) return
      return <Badge color={value === 1 ? 'green' : 'red'} text={valueFormatted || value} />
    }
    case 'routeId': {
      return <ActionCell {...(p as TCellParams<'routeId'>)} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const TplRoute = () => {
  useTplRouteList() // 放最顶部

  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 180,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )
  const columnDefs = useMemo(
    () => [
      {
        field: 'routeNo',
        headerName: '路由编号',
        flex: 0.01,
        minWidth: 114,
      } satisfies TCol<'routeNo'>,
      {
        field: 'templateCn',
        headerName: '中文模板',
        flex: 2,
        minWidth: 210,
        autoHeight: true,
        wrapText: true,
      } satisfies TCol<'templateCn'>,
      {
        field: 'templateEn',
        headerName: '英文模板',
        flex: 2,
        minWidth: 210,
        autoHeight: true,
        wrapText: true,
      } satisfies TCol<'templateEn'>,
      {
        field: 'dynamicField',
        headerName: '动态字段',
        minWidth: 210,
      } satisfies TCol<'dynamicField'>,
      {
        field: 'routeNode',
        headerName: '路由节点',
        valueFormatter: ({ value }) => getRouteNodeName(value) || '',
      } satisfies TCol<'routeNode'>,
      {
        field: 'logisticsStatus',
        headerName: '物流状态',
        flex: 0.01,
        minWidth: 114,
        valueFormatter: ({ value }) => getLogisticsStatusName(value) || '',
      } satisfies TCol<'logisticsStatus'>,
      {
        field: 'routeType',
        headerName: '路由类型',
        flex: 0.01,
        minWidth: 114,
        valueFormatter: ({ value }) => getRouteTypeName(value) || '',
      } satisfies TCol<'routeType'>,
      {
        field: 'actionFlag',
        headerName: '需跟进',
        flex: 0.01,
        minWidth: 100,
        valueFormatter: ({ value }) => getBooleanName(value) || '',
      } satisfies TCol<'actionFlag'>,
      {
        field: 'visibleFlag',
        headerName: '客户可见',
        flex: 0.01,
        minWidth: 114,
        valueFormatter: ({ value }) => getBooleanName(value) || '',
      } satisfies TCol<'visibleFlag'>,
      {
        field: 'routeId',
        headerName: '操作',
        flex: 0.01,
        width: 100,
        minWidth: 100,
        pinned: 'right',
      } satisfies TCol<'routeId'>,
    ],
    [],
  )

  // 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    return {
      statusPanels: [
        {
          statusPanel: UnifiedPagination,
          statusPanelParams: UnifiedPagination.defineProps({
            current: page,
            pageSize: size,
            total: data?.total,
            onChange: (page, size) => {
              setReqData({ page, size })
              getData(true)
            },
          }),
        },
      ],
    }
  }, [data?.total, getData, page, setReqData, size])

  // 清理，保留筛选条件
  useEffect(
    () => () =>
      useBoundStore.setState({ ...useBoundStore.getInitialState(), reqData: useBoundStore.getState().reqData }, true),
    [],
  )

  return (
    <div className={styles.box}>
      <div className={styles.header}>
        <div className={styles.header_filter}>
          <Filter />
        </div>
        <div className={styles.header_action}>
          <Button
            type="primary"
            onClick={() => {
              AddOrEditTplRouteDrawer.open({
                routeId: null,
                onSuccess: () => {
                  setReqData({ page: 1 })
                  getData(true)
                },
              })
            }}
          >
            添加路由模板
          </Button>
        </div>
      </div>
      <div className={styles.main}>
        <CusAgGrid<ITplRouteListItem>
          ref={gridRef}
          loading={loading}
          rowData={data?.records}
          defaultColDef={defaultColDef}
          columnDefs={columnDefs}
          statusBar={statusBar}
        />
      </div>
      <popupSlot.Slot />
    </div>
  )
}
